package com.stn.zjx.givingtreasure.fragment.main;

import android.content.res.Resources;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.activity.msg.MsgTypeListActivity;
import com.stn.zjx.givingtreasure.adapter.MainFragmentAdapter;
import com.stn.zjx.givingtreasure.event.ActiveFragmentEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.base.BaseMainFragment;
import com.stn.zjx.givingtreasure.fragment.active.DynamicFragment;
import com.stn.zjx.givingtreasure.fragment.active.PrivateFragment;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.MsgNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.widget.NoScrollViewPager;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActiveFragment extends BaseMainFragment implements TabLayout.BaseOnTabSelectedListener {
    public View rootView;
    @BindView(R.id.msg_iv)
    ImageView msgIv;
    @BindView(R.id.msg_rl)
    RelativeLayout msgRl;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    NoScrollViewPager viewpager;
    @BindView(R.id.location_status)
    public TextView locationStatus;



    private DynamicFragment dynamic;
    private PrivateFragment privates;
    private MainFragmentAdapter mainAdapter;
    @BindArray(value = R.array.main_active_ar)
    String[] main_active_ar;
    private BadgeView badgeView;

    //更新事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFragmentActive(ActiveFragmentEvent event){
          if(event.flag==ActiveFragmentEvent.ACTIVE_LOCATION_STATUS_CHANGE){
             locationStatus.setText(event.data);
          }
    }


    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        if (rootView == null) {
            rootView = View.inflate(activity, R.layout.fragment_main_active, null);
            ButterKnife.bind(this, rootView);

        }
        return rootView;
    }

    @Override
    public void initData() {
        badgeView = BadgeFactory.create(activity)
                .setTextColor(getResources().getColor(R.color.white))
                .setWidthAndHeight(20, 20)
                .setBadgeBackground(getResources().getColor(R.color.red))
                .setTextSize(10)
                .setBadgeGravity(Gravity.RIGHT | Gravity.TOP)
                .setBadgeCount("0")
                .setShape(BadgeView.SHAPE_CIRCLE)
                .bind(msgRl);
        badgeView.setVisibility(View.GONE);
        badgeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity, MsgTypeListActivity.class);
            }
        });

        setupTabIcons();
    }


    //初始化底部选项文字以及图片
    public void setupTabIcons() {
        if (main_active_ar == null || main_active_ar.length == 0 || tablayout == null) {
            return;
        }
        int size = main_active_ar.length;
        viewpager.setOffscreenPageLimit(main_active_ar.length - 1);
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(dynamic = new DynamicFragment());
        fragmentList.add(privates = new PrivateFragment());
        viewpager.setAdapter(mainAdapter = new MainFragmentAdapter(activity, getChildFragmentManager(), fragmentList));
        viewpager.setNoScroll(true);


        for (int i = 0; i < size; i++) {
            tablayout.addTab(tablayout.newTab().setCustomView(getTabView(i)));
        }
        //监听被选中子菜单
        tablayout.addOnTabSelectedListener(this);

    }

    /**
     * 获取子菜单
     *
     * @param position 当前位置
     * @return 得到子菜单选项
     */
    //得到底部子菜单选项
    public View getTabView(int position) {
        View tabView = View.inflate(activity, R.layout.item_main_tab_title, null);
        TextView txt_title = tabView.findViewById(R.id.txt_title);
        txt_title.setText(main_active_ar[position]);

        if (position == 0) {
            txt_title.setTextColor(getResources().getColor(R.color.colorAccent));
            txt_title.getPaint().setFakeBoldText(true);
            //  img_title.setImageResource(imgsMenu[position * 2]);
        } else {
            txt_title.setTextColor(getResources().getColor(R.color.default_black));
            txt_title.getPaint().setFakeBoldText(false);
            //  img_title.setImageResource(imgsMenu[position * 2 + 1]);
        }
        return tabView;
    }

    /**
     * 当被选中变化子菜单内容
     *
     * @param tab 子菜单组件
     */
    //选中时tab字体颜色和icon
    private void changeTabSelect(TabLayout.Tab tab) {
        //如果不等于空
        assert tab.getCustomView() != null;

        TextView txt_title = tab.getCustomView().findViewById(R.id.txt_title);
        int position = tab.getPosition();
        txt_title.setTextColor(getResources().getColor(R.color.colorAccent));
        txt_title.getPaint().setFakeBoldText(true);
//        img_title.setImageResource(main_active_ar[position * 2]);
        viewpager.setCurrentItem(tablayout.getSelectedTabPosition(), false);
//        AnimationSet animationSet = new AnimationSet(true);
//        ScaleAnimation scaleAnimation = new ScaleAnimation(1,1.2f,1,1.2f,
//                Animation.RELATIVE_TO_SELF,1.0f,Animation.RELATIVE_TO_SELF,1.0f);
//        //3秒完成动画
//        scaleAnimation.setDuration(100);
//        //将AlphaAnimation这个已经设置好的动画添加到 AnimationSet中
//        animationSet.addAnimation(scaleAnimation);
//        //启动动画
//        img_title .startAnimation(animationSet);
    }

    /**
     * 没有被选中变化子菜单内容
     *
     * @param tab 子菜单组件
     */
    //默认tab字体颜色和icon
    private void changeTabNormal(TabLayout.Tab tab) {
        assert tab.getCustomView() != null;

        TextView txt_title = tab.getCustomView().findViewById(R.id.txt_title);
        int position = tab.getPosition();
        txt_title.setTextColor(getResources().getColor(R.color.default_black));
        txt_title.getPaint().setFakeBoldText(false);
//        img_title.setImageResource(imgsMenu[position * 2 + 1]);

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        changeTabSelect(tab);
        viewpager.setCurrentItem(tab.getPosition(), false);
    }

    //监听子菜单没被选中
    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        changeTabNormal(tab);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    public void initUser() {
        if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
            initDefault();
            return;
        }
        User userOnline = UserService.getInstance(activity).getOnlineLoginUser();
        MsgNetImpl
                .query_get_no_read_all_msg(userOnline.getToken(), userOnline.getUserId() + "_query_get_no_read_all_msg",
                        new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    query_get_no_read_all_msg(response.body());
                                }

                            }

                            @Override
                            public void onCacheSuccess(Response<String> response) {
                                super.onCacheSuccess(response);
                                if (response.isSuccessful() && !activity.isFinishing()) {
                                    query_get_no_read_all_msg(response.body());
                                }
                            }
                        });


    }

    public void initDefault() {
        badgeView.setVisibility(View.GONE);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (rootView != null) {
                initUser();
            }
        }
    }

    //获取未读消息
    public void query_get_no_read_all_msg(String data) {
        if (data == null || data.length() == 0) {
            return;
        }
        try {
            JSONObject result = new JSONObject(data);
            switch (result.getInt(BaseApi.KEY_STATUS)) {
                case BaseApi.REQUEST_SUCCESS_CODE:
                    int msg_count = result.getInt("data");
                    if (msg_count == 0) {
                        badgeView.setVisibility(View.GONE);
                    } else {
                        if (msg_count >= 99) {
                            badgeView.setBadgeCount("99+");
                        } else {
                            badgeView.setBadgeCount("" + msg_count);
                        }
                        badgeView.setVisibility(View.VISIBLE);
                    }
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @OnClick({R.id.msg_iv, R.id.msg_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //消息
            case R.id.msg_iv:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity, MsgTypeListActivity.class);
                break;
                //消息
            case R.id.msg_rl:
                if (UserService.getInstance(activity).getOnlineLoginUser() == null) {
                    RxActivityTool.skipActivity(activity, UserLoginActivity.class);
                    return;
                }
                RxActivityTool.skipActivity(activity, MsgTypeListActivity.class);
                break;


        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }





}
